package com.dfrz.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dfrz.bean.User;
import com.dfrz.service.IUserService;
import com.dfrz.utils.ResuleUtiles;
import com.dfrz.utils.Result;
import com.dfrz.utils.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Create by keyan on 2021/7/29 11:19
 */

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    IUserService userService;


    @RequestMapping("/viewrole")
    public Result viewRole(){
        List<Map<String, String>> maps = userService.statisticalRole();
        Result result = null;
        if (maps.size()>0){
            result = ResuleUtiles.success(maps,maps.size());
        }else {
            result = ResuleUtiles.unKnowError(maps);
        }
        return result;
    }

    @RequestMapping("/toupdate/{id}")
    public ModelAndView toUpDate(@PathVariable Integer id){
        ModelAndView mv = new ModelAndView();
        User user = userService.getUserById(id);
        mv.addObject(user);
        mv.setViewName("user_update");
        return mv;
    }


    @RequestMapping("/update")
    public Result update(User user){
        Result result = null;
        if(user.getId()==null){
            result = ResuleUtiles.userNotExists(user);
            return  result;
        }
        int i = userService.updateUser(user);
        if (i>0){
             result = ResuleUtiles.success(i, i);
        }else {
             result = ResuleUtiles.unKnowError(user);
        }
        return result;
    }


    @RequestMapping("/doaddUser")
    public Result addUser(User user){
        int i = userService.addUser(user);
        Result result = null;
        if (i>0){
             result = ResuleUtiles.success(i,null);
        }else {
            result = ResuleUtiles.unKnowError(i);
        }
        return result;
    }

    @RequestMapping("/toaddUser")
    public ModelAndView toAddUser(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("user_add");
        return mv;
    }

    @RequestMapping("/list")
    public Result getUsers(){
        List<User> userList = userService.getUsers();
        Result result = ResuleUtiles.success(userList,userList.size());
        return result;
    }

    @RequestMapping("/listparms")
    public Result getUsersParm(String uname){
        Map<String,String> parm = new HashMap<>();
        parm.put("uname",uname);
        List<User> userList = userService.getUsersParm(parm);
        Result result = ResuleUtiles.success(userList,userList.size());
        return result;
    }

    @RequestMapping("/listpage")
    public Result getUserByPage(String uname,String gender,Integer page,Integer limit){
        Map<String,String> parm = new HashMap<>();
        parm.put("uname",uname);
        parm.put("gender",gender);
        IPage<User> iPage = userService.getUserByPage(parm, page, limit);
        Result result = ResuleUtiles.success(iPage.getRecords(),(int) iPage.getTotal());
        return result;
    }

    @RequestMapping("/tolist")
    public ModelAndView toList(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("user_list");
        return mv;
    }

    @RequestMapping("/del/{id}")
    public Result delUserById(@PathVariable Integer id){
        int i = userService.delUserById(id);
        Result result;
        if (i>0){
              result = ResuleUtiles.success(i,0);
        }else{
             result = ResuleUtiles.userNotExist(i);
        }
        return result;
    }

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {
        Map<String,Object> map = new HashMap<>();
        Result result = null;
        //文件名
        String filename = file.getOriginalFilename();
        //上传路径
        String filePath = "E:\\springboot_upload";
        File destFile = new File(filePath + File.separator + filename);
        System.out.println("文件:" + filePath + File.separator + filename);
        try {
            //文件IO输入输出
            file.transferTo(destFile);
            map.put("src",filename);
             result = ResuleUtiles.success(map,1);
        } catch (IOException e) {
            e.printStackTrace();
            result.setCode(-1);
            result.setMsg("上传失败");
        }
        return result;
    }

    /**
     * 头像下载
     */
    @GetMapping("/downpic")
    public void downpic(HttpServletRequest request, HttpServletResponse response) {
//        System.out.println("开始下载>>>>>>");
        //String fileName = "qq.docx";// 文件名
        String fileName = request.getParameter("fileName");
        if (fileName != null) {
            //设置文件路径
            File file = new File("E:\\springboot_upload\\" + fileName);
            //File file = new File(realPath , fileName);
            if (file.exists()) {
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally { // 做关闭操作
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}
